/*
 * Created: Author: Aléx Carvalho / Date: Jan 28, 2015
 * 
 * Changed: $Author: ac280593@gmail.com $ / $Date: 2015-06-11 01:01:39 -0300 (Thu, 11 Jun 2015) $
 */
package com.cpm.repository.jpa;

import com.cpm.entities.Folder;
import com.cpm.entities.Folder_;
import com.cpm.entities.StrategicPlan;
import com.cpm.repository.StrategicPlanRepository;
import com.cpm.wrapper.Performance;
import javax.persistence.Query;

public class StrategicPlanRepositoryJpa extends GenericCrudRepositoryJpa<StrategicPlan> implements StrategicPlanRepository {

    @Override
    public Performance calculePerformance(StrategicPlan parent) {

        String sql = "SELECT AVG(" + Folder_.performance.getName() + ") FROM "
                + Folder.class.getSimpleName()
                + " WHERE " + Folder_.parentId.getName() + " = " + parent.getId()
                + " AND " + Folder_.parentFamily.getName() + " = " + parent.getFamily().getId()
                + " AND " + Folder_.performance.getName() + " IS NOT NULL";

        Query query = entityManager.createQuery(sql);

        Number value = (Number) query.getSingleResult();

        return value != null ? new Performance(value.floatValue()) : null;
    }
}
